package com.codegeek.framework.web.timer;

import com.alibaba.fastjson.JSON;
import com.codegeek.common.utils.DateUtils;
import com.codegeek.project.slope.domain.SlopeCamera;
import com.codegeek.project.slope.service.ISlopeCameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Configuration
@EnableScheduling
public class RefreshCameraToken {

//    private String appKey = "845681a83d794d72989b55122117a094";
//    private String appSecret = "324236b747e50bf59d20956c920916d0";
    private String tokenUrl = "https://open.ys7.com/api/lapp/token/get";

    @Autowired
    ISlopeCameraService slopeCameraService;

    @Scheduled(cron = "0 0 0 1/1 * ?")//每天执行一次
    public void refreshToken(){
        SlopeCamera slopeCamera = new SlopeCamera();
        List<SlopeCamera> cameraList = slopeCameraService.selectSlopeCameraList(slopeCamera);
        for(SlopeCamera camera : cameraList){
            Date tokenTime =  camera.getTokenTime();
            if(DateUtils.getDatePoor2(tokenTime,new Date())<24){
                String params = camera.getDevice().getParamValues();
                if(params!=null&&!params.equals("")) {
                    camera.setAccessToken(getReaToken(params.split(",")[0], params.split(",")[1]));
                    camera.setTokenTime(new Date());
                }
                slopeCameraService.updateSlopeCamera(camera);
            }
        }
    }

    public String getReaToken(String appKey,String appSecret){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("appKey",appKey);
        map.add("appSecret",appSecret);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( tokenUrl, request , String.class );
        System.out.println(response.getBody());
        Map<String,Object> dataMap = JSON.parseObject(response.getBody(), Map.class);
        Map<String,Object> tokenMap = JSON.parseObject(dataMap.get("data").toString(),Map.class);
        String accessToken = tokenMap.get("accessToken").toString();
        return accessToken;
    }
}
